//
//  EditInfoViewController.m
//  parent
//
//  Created by yanzhen on 15/7/17.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "EditInfoViewController.h"
#import "Config.h"
#import "UIImageView+WebCache.h"
#import "CameraGalleryManager.h"
#import "AFAppClient.h"
#import "Tool.h"
#import "ChangeInterestViewController.h"
#import "CityViewController.h"

@interface EditInfoViewController ()<UIActionSheetDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *photo;
@property (weak, nonatomic) IBOutlet UILabel *age;
@property (weak, nonatomic) IBOutlet UILabel *birthday;
@property (weak, nonatomic) IBOutlet UILabel *hobby;
@property (weak, nonatomic) IBOutlet UILabel *location;
@property UIDatePicker *datePicker;
@property UITextField *textField;
@end

@implementation EditInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"完善资料";
    [self CustomBackButton];
    
    
    _datePicker = [[UIDatePicker alloc]init];
    [_datePicker setMaximumDate:[NSDate date]];
    [_datePicker setMinimumDate:[NSDate dateWithTimeIntervalSinceNow:-1 * 3600* 24 * 365 *100]];
    /*
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat: @"yyyy-MM-dd "];
    NSDate *destDate= [dateFormatter dateFromString:dateString];
     */
    [_datePicker setDate:[NSDate dateWithTimeIntervalSinceNow:-1 * 3600* 24 * 365*50]];
    _datePicker.datePickerMode = UIDatePickerModeDate;
    [_datePicker addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];
    
    _textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 260, 0, 0)];
    _textField.placeholder=@"";
    [_textField setInputView:_datePicker];
    [self.view addSubview:_textField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh_data:) name:kReloadInfo object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change_city:) name:kChangeCity object:nil];
    [self refresh_data:nil];
}

-(void)refresh_data:(id)sender
{
    NSDictionary *info = [[Config Instance]getUInfo];
    [_photo sd_setImageWithURL:[NSURL URLWithString:[info objectForKey:@"pic"]] placeholderImage:[UIImage imageNamed:@"default_avatar"]];
    if(![[info objectForKey:@"birthday"] isEqual:[NSNull null]]){
        _birthday.text = [info objectForKey:@"birthday"];
    }else{
        _birthday.text = @"";
    }
    if(![[info objectForKey:@"age"] isEqual:[NSNull null]]){
        _age.text = [info objectForKey:@"age"];
    }else{
        _age.text = @"";
    }
    if(![[info objectForKey:@"interest"] isEqual:[NSNull null]]){
        _hobby.text = [info objectForKey:@"interest"];
    }else{
        _hobby.text = @"";
    }
    
    if(![[info objectForKey:@"city"] isEqual:[NSNull null]]){
        _location.text = [info objectForKey:@"city"];
    }else{
        _location.text = @"";
    }

}
#pragma mark ----------关于生日选择---------------

-(void)changeDate:(UIDatePicker *)picker
{
    NSDateFormatter *format = [[NSDateFormatter alloc]init];
    [format setDateFormat:@"yyyy-MM-dd"];
    
    //_birthday.text = [format stringFromDate:picker.date];
    
    NSString *birth_str = [format stringFromDate:picker.date];
    NSDate *now = [NSDate new];
    [format setDateFormat:@"yyyy"];
    NSUInteger nowY = [[format stringFromDate:now]integerValue];
    NSUInteger sY =[[format stringFromDate:picker.date]integerValue];
//    [format setDateFormat:@"yyyy"];
//    _babyY =[format stringFromDate:picker.date];
//    [format setDateFormat:@"MM"];
//    _babyM = [format stringFromDate:picker.date];
//    [format setDateFormat:@"dd"];
//    _babyD = [format stringFromDate:picker.date];
//    
//    _babyinfo.birthy = [_babyY integerValue];
//    _babyinfo.birthm = [_babyM integerValue];
//    _babyinfo.birthd = [_babyD integerValue];
    NSDictionary *param = @{@"uid":@([[Config Instance]getUID]),@"field":@"birthday",@"value":birth_str
                            };
    [self showHud:@"正在修改" isDim:YES];
    [[AFAppClient sharedManager]getWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,kMemberEditInfo] withParameters:param success:^(NSDictionary *responseObject) {
        if([[responseObject objectForKey:@"code"] integerValue]== 1){
            [self showHudComplete:@"修改成功" success:YES];
            _birthday.text = birth_str;
            _age.text = [NSString stringWithFormat:@"%d",(nowY-sY)];
            [Tool reSetInfo];
        }else{
            [self showHudComplete:@"修改失败" success:NO];
        }
    } failure:^(NSError *error) {
        [self showHudComplete:@"网络连接失败" success:NO];
    }];
}

-(void)change_city:(id)sender
{
   
    NSString *city = [[NSUserDefaults  standardUserDefaults]objectForKey:@"city"];
    NSDictionary *param = @{@"uid":@([[Config Instance]getUID]),@"field":@"city",@"value":city
                            };
    [self showHud:@"正在修改" isDim:YES];
    [[AFAppClient sharedManager]getWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,kMemberEditInfo] withParameters:param success:^(NSDictionary *responseObject) {
        if([[responseObject objectForKey:@"code"] integerValue]== 1){
            [self showHudComplete:@"修改成功" success:YES];
            _location.text = city;
            [Tool reSetInfo];
        }else{
            [self showHudComplete:@"修改失败" success:NO];
        }
    } failure:^(NSError *error) {
        [self showHudComplete:@"网络连接失败" success:NO];
    }];
}

- (IBAction)edit_avatar:(id)sender {
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"选取照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册",nil];
    [sheet showInView:self.view];

}
- (IBAction)edit_age:(id)sender {
    
}
- (IBAction)edit_birth:(id)sender {
    [_textField becomeFirstResponder];
    
}
- (IBAction)edit_interest:(id)sender {
    ChangeInterestViewController *interest = [ChangeInterestViewController new];
    interest.interest = _hobby.text;
    [self.navigationController pushViewController:interest animated:YES];
}
- (IBAction)edit_city:(id)sender {
    CityViewController *cityView = [[CityViewController alloc]init];
    cityView.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:cityView animated:YES];
}

- (BOOL)checkCamera {
    BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    if(!isCamera) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"此设备没有摄像头" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }else{
        return YES;
    }
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //    UIImagePickerControllerSourceType sourceType;
    if(buttonIndex == 0) {
        if([self checkCamera]){
            //            sourceType = UIImagePickerControllerSourceTypeCamera;
            //            [self openGallery:sourceType];
            
            [[CameraGalleryManager getInstanse] takePhoto:self finishBlock:^(UIImage *img, NSString * avaURL) {
                if (img) {
                    _photo.image = img;
                    NSDictionary *param = @{@"type":@(1),@"uid":@([[Config Instance]getUID]),@"image.jpg":img};
                    [self showHud:@"正在修改" isDim:YES];
                    [[AFAppClient sharedManager]postWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,kMemberPhoto] withParameters:param success:^(NSDictionary *responseObject) {
                        if([[responseObject objectForKey:@"code"] integerValue]== 1){
                            [self showHudComplete:@"修改成功" success:YES];
                            [Tool reSetInfo];
                        }else{
                            [self showHudComplete:@"修改失败" success:NO];
                        }
                    } failure:^(NSError *error) {
                        [self showHudComplete:kNoNetwork success:NO];
                    }];
                }
            }];
        }else{
            return;
        }
    }else if(buttonIndex == 1){
        //        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //        [self openGallery:sourceType];
        [[CameraGalleryManager getInstanse] gallerySelect:self finishBlock:^(UIImage *img, NSString * avaURL) {
            if (img) {
                _photo.image = img;
                NSDictionary *param = @{@"type":@(1),@"uid":@([[Config Instance]getUID]),@"image.jpg":img};
                [self showHud:@"正在修改" isDim:YES];
                [[AFAppClient sharedManager]postWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,kMemberPhoto] withParameters:param success:^(NSDictionary *responseObject) {
                    if([[responseObject objectForKey:@"code"] integerValue]== 1){
                        [self showHudComplete:@"修改成功" success:YES];
                        [Tool reSetInfo];
                    }else{
                        [self showHudComplete:@"修改失败" success:NO];
                    }
                } failure:^(NSError *error) {
                    [self showHudComplete:kNoNetwork success:NO];
                }];
                
            }
        }];
    }
}

-(void)openGallery:(UIImagePickerControllerSourceType) source{
    //初始化类
    UIImagePickerController *pick = [[UIImagePickerController alloc] init];
    //指定图片来源
    pick.sourceType = source;
    //表示用户可编辑图片。
    pick.allowsEditing = YES;
    //代理
    pick.delegate = self;
    [self presentViewController:pick animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController: (UIImagePickerController *)picker didFinishPickingMediaWithInfo: (NSDictionary *)info {
    
    UIImage *image = [info objectForKey: @"UIImagePickerControllerEditedImage"];
    NSLog(@"%@", image);
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void) imagePickerControllerDidCancel: (UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
